import { prisma } from '../../utils/prisma'
import { assertChildOwnership } from '../../utils/guard'
import { getDateRangeDay } from '../../utils/date'
import { z } from 'zod'

export default eventHandler(async (event) => {
  const q = getQuery(event)
  const schema = z.object({ childId: z.string(), date: z.string() })
  const parsed = schema.safeParse(q)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const childId = Number(parsed.data.childId)
  if (!Number.isFinite(childId)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })
  await assertChildOwnership(event, childId)
  const { start, end } = getDateRangeDay(parsed.data.date)
  const ledger = await prisma.pointsLedger.findMany({ where: { childId, occurredAt: { gte: start, lte: end } } })
  const total = ledger.reduce((s, l) => s + (l.kind === 'earn' ? l.amount : l.kind === 'spend' ? -l.amount : l.amount), 0)
  return { total }
})


